package com.example.blog.config;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.example.blog.entity.Photo;
import com.example.blog.entity.Result;
import kong.unirest.HttpResponse;
import kong.unirest.Unirest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Slf4j
@Controller
public class SmmsConfig {

    @Value("${smms.base-url}")
    private String baseUrl;
    @Value("${smms.upload-path}")
    private String uploadPath;
    @Value("${smms.delete-path}")
    private String deletePath;
    @Value("${smms.smms-token}")
    private String smmsToken;

    @Value("${smms.allow-format}")
    private String allowFormats;

    @Bean(initMethod = "init", destroyMethod = "destroy")
    public SmmsDao smmsDao(){
        return new SmmsDao() {

            List<String> formats;

            @Override
            public void init() throws Exception{
                if(null==baseUrl){
                    log.error("smms配置缺少服务器地址(base-url)异常");
                    throw new Exception("smms配置缺少服务器地址(base-url)异常");
                }
                if(null==smmsToken){
                    log.error("smms配置缺少token(smms-token)异常");
                    throw new Exception("smms配置缺少token(smms-token)异常");
                }
                if(null==uploadPath){
                    log.error("smms配置缺少上传api路径(upload-path)异常");
                    throw new Exception("smms配置缺少上传api路径(upload-path)异常");
                }
                if(null==deletePath){
                    log.error("smms配置缺少删除api路径(delete-path)异常");
                    throw new Exception("smms配置缺少删除api路径(delete-path)异常");
                }

                formats = new ArrayList<>(Arrays.asList(allowFormats.split(",")));
            }

            @Override
            public void destroy() {
                if(null != formats){
                    formats = null;
                }
            }

            @Override
            public Result upload(MultipartFile imageFile) {

                // 获取文件类型 格式：image/png
                String contentType = Objects.requireNonNull(imageFile.getContentType()).toLowerCase();
                contentType = contentType.substring(contentType.indexOf("/")+1);
                if(!formats.contains(contentType)){
                    return Result.fail("不支持"+contentType+"文件类型");
                }
                final String url = String.format("%s%s", baseUrl, uploadPath);
                File file = null;
                try {
                    file = File.createTempFile("img", contentType);
                    imageFile.transferTo(file);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                HttpResponse<String> response = Unirest.post(url)
                        .header("Authorization", smmsToken)
                        .field("smfile", file)
                        .asString();

                file.delete();

                final JSONObject jsonObject = JSON.parseObject(response.getBody());

                System.out.println(jsonObject);

                final String res = jsonObject.getString("success");

                if(res.equals("false")){
                    String code = jsonObject.getString("code");
                    if(code.equals("image_repeated")){
                        return Result.ok(code, jsonObject.getString("images"));
                    }
                    return Result.fail(code);
                }
                final JSONObject photoJson = JSONObject.parseObject(jsonObject.getString("data"));

                Photo photo = new Photo();
                photo.setHeight(photoJson.getInteger("height"));
                photo.setUrl(photoJson.getString("url"));
                photo.setPhotoHash(photoJson.getString("hash"));
                photo.setWidth(photoJson.getInteger("width"));
                photo.setSize(photoJson.getInteger("size"));
                return Result.ok(photo);
            }

            @Override
            public Result delete(String hash) {
                final String url = String.format("%s%s/%s", baseUrl, deletePath, hash);
                HttpResponse<String> response = Unirest.get(url)
                        .header("Authorization", smmsToken)
                        .asString();
                return Result.ok(JSON.parseObject(response.getBody()).getString("message"));
            }

            private void close(AutoCloseable...acs){
                for (AutoCloseable ac : acs) {
                    if(null != ac){
                        try {
                            ac.close();
                        } catch (Exception e) {
                            log.error("释放资源异常",e);
                        }
                    }
                }
            }
        };
    }

}
